#include <stdio.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#define ARGS_CHECK(argc, num)                 \
    {                                         \
        if (argc != num)                      \
        {                                     \
            fprintf(stderr, "args error !n"); \
            return -1;                        \
        }                                     \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
int main(int argc, char *argv[])
{
    ARGS_CHECK(3, argc);
    int fd_s = socket(PF_INET, SOCK_DGRAM, 0);
    ERROR_CHECK(-1, fd_s, "socket");
    //
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(atoi(argv[2]));
    saddr.sin_addr.s_addr = inet_addr(argv[1]);
    // bind(fd_s, (void *)&saddr, sizeof saddr);
    // ERROR_CHECK(-1, fd_s, "bind");
    char buf[1024];
    socklen_t len = sizeof saddr;
    while (1)
    {
        fgets(buf, 1024, stdin);
        if (-1 == sendto(fd_s, buf, 1024, 0, (void *)&saddr, len))
        {
            perror("sendto");
            continue;
        }
        if (strncmp(buf, "DN", 2) == 0)
        {
    
            int fd_src = open("hahahimg.png", O_WRONLY | O_CREAT|O_TRUNC, 0664);
            ERROR_CHECK(-1, fd_src, "open");
            int ret_val;
            while (1)
            {

                if (ret_val == recvfrom(fd_s, buf, 1024, 0, (void *)&saddr, &len))
                {
                    perror("recvfrom");
                    return -1;
                }
                int ret = atoi(buf);
                while (ret != recvfrom(fd_s, buf, ret, MSG_PEEK, (void *)&saddr, &len))
                    ;

                ret_val = recvfrom(fd_s, buf, ret, 0, (void *)&saddr, &len);
                
                if (strncmp(buf,"over",4) == 0)
                {
                    puts(buf);
                    puts("下载完成");
                    break;
                }
                else if (-1 == ret_val)
                {
                    perror("recvfrom");
                    break;
                }
                write(fd_src, buf, ret);
            }
            close(fd_src);
        }
    }
    close(fd_s);
    return 0;
}
